package shop.converter;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import shop.IService;
import shop.model.Brand;

import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;

@Component
@FacesConverter(forClass = Brand.class)
public class BrandConverter implements Converter {
    @Autowired
    private IService<Brand> brandService;

    @Override
    public Object getAsObject(FacesContext context, UIComponent component, String value) {
        if ("".equals(value)) {
            return null;
        }

        Long brandId = Long.valueOf(value);
        return brandService.read(brandId);
    }

    @Override
    public String getAsString(FacesContext context, UIComponent component, Object value) {
        if ("".equals(value.toString())) {
            return null;
        }

        return ((Brand) value).getId().toString();
    }
}
